package com.xjd.hibernate.entities;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class HibernateTest {
	private SessionFactory sessionFactory;
	private Session session;
	private Transaction transaction;

	@Before
	public void init() {
		System.out.println("init");
		Configuration configuration = new Configuration().configure();
		ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
				.buildServiceRegistry();
		sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		session = sessionFactory.openSession();
		transaction = session.beginTransaction();
	}

	@After
	public void destroy() {
		System.out.println("destory");
		transaction.commit();
		session.close();
		sessionFactory.close();
	}

	@Test
	public void testSessionCache() {
		News news0 = new News("java", "tonggang", new Date());
		session.save(news0);
		System.out.println("--------------------------------------------");
		News news1 = (News) session.get(News.class, 1);
		System.out.println(news1);
		News news2 = (News) session.get(News.class, 1);
		System.out.println(news2);
	}

	@Test
	public void testSessionFlush() {
		News news = (News) session.get(News.class, 1);
		news.setAuthor("xiaotong");
		// session.flush();
		// System.out.println("flush");
		News news3 = (News) session.createCriteria(News.class).uniqueResult();
		System.out.println(news3.toString());
	}

	@Test
	public void testRefresh() {
		News news = (News) session.get(News.class, 1);
		System.out.println(news);
		session.refresh(news);
		System.out.println(news);
	}

	@Test
	public void testClear() {
		News news = (News) session.get(News.class, 1);
		System.out.println(news.toString());
		session.clear();
		News news1 = (News) session.get(News.class, 1);
		System.out.println(news1.toString());
	}

}
